package com.ynet.middleground.mobile.approve.service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import org.apache.dubbo.config.annotation.Reference;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.core.util.IDUtil;
import com.ynet.middleground.contract.bean.BatchSignPdfAppointMobileReq;
import com.ynet.middleground.contract.bean.SendAppointSignMobileCodeReq;
import com.ynet.middleground.contract.bean.SigningParamBean;
import com.ynet.middleground.contract.bean.UserSealReq;
import com.ynet.middleground.contract.dto.MultiSignedResultDTO;
import com.ynet.middleground.contract.dto.UserSealDTO;
import com.ynet.middleground.contract.service.SealService;
import com.ynet.middleground.contract.service.SignService;
import com.ynet.middleground.mobile.approve.constant.ErrorMessageConstant;
import com.ynet.middleground.mobile.approve.constant.SystemConstant;
import com.ynet.middleground.mobile.approve.dao.SignCodeMapper;
import com.ynet.middleground.mobile.approve.entity.SignCode;
import com.ynet.middleground.mobile.approve.request.SendCodeReq;
import com.ynet.middleground.mobile.approve.response.SealInfoDTO;
import com.ynet.middleground.user.dto.UserInfoDto;

/**
 * @ClassName ContractCenterService
 * @Description 合约中心
 * @Author liwq
 * @Date 2021/3/23 22:04
 * @Version 1.0
 */
@Service
public class ContractCenterService {

    @Reference(version = "0.0.1", check = false)
    SignService signService;

    @Reference(version = "0.0.1", check = false)
    SealService sealService;

    @Autowired
    UserCenterService userCenterService;

    @Autowired
    Mapper mapper;

    @Autowired
    SignCodeMapper signCodeMapper;

    /**
     * 电子签章-手机号验证码获取
     * 
     * @param sendCodeReq
     * @return
     */
    public ServiceResult<Object> sendCode(SendCodeReq sendCodeReq) {
        // step1: 准备参数
        ServiceResult result = new ServiceResult();
        SendAppointSignMobileCodeReq req = new SendAppointSignMobileCodeReq();
        req.setTraceId(IDUtil.getSecureRandomId());
        req.setChannel(SystemConstant.CHANNEL);
        req.setOperationUserId(sendCodeReq.getUserId());
        req.setRequestTime(new Date());
        req.setAccountId(sendCodeReq.getAccountId());
        req.setMobile(sendCodeReq.getMobile());

        // step2: 先校验，校验通过后，转调合约中台，并将验证码结果返回
        SignCode signCode = null;
        LocalDateTime lastSendCodeTime;
        LambdaQueryWrapper<SignCode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SignCode::getTaskId, sendCodeReq.getTaskId());
        queryWrapper.eq(SignCode::getUserId, sendCodeReq.getUserId());
        List<SignCode> signCodes = signCodeMapper.selectList(queryWrapper);
        if (signCodes != null && signCodes.size() > 0) {
            signCode = signCodes.get(0);
            lastSendCodeTime = signCode.getGmtModified();
            Duration duration = Duration.between(lastSendCodeTime, LocalDateTime.now());
            Long times = duration.toMillis();
            if (times < 60 * 1000) {
                throw new BusinessException(ErrorMessageConstant.ECUC0023_MESSAGE, ErrorMessageConstant.ECUC0023_CODE);
            }
        }
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "移动审批调用电子签章-手机号验证码获取服务,reqParams: {}",
            sendCodeReq.toString());
        result = signService.sendAppointSignMobileCode(req);

        // step3: 将短信信息保存到表里
        if (signCode != null) {
            signCode.setGmtModified(LocalDateTime.now());
            signCode.setModifiedBy(sendCodeReq.getUserId());
            signCodeMapper.updateById(signCode);
        }
        if (signCode == null) {
            signCode = new SignCode();
            signCode.setUserId(sendCodeReq.getUserId());
            signCode.setTaskId(sendCodeReq.getTaskId());
            signCode.setPhone(sendCodeReq.getMobile());
            signCode.setGmtCreate(LocalDateTime.now());
            signCode.setCreateBy(sendCodeReq.getUserId());
            signCode.setGmtModified(LocalDateTime.now());
            signCode.setModifiedBy(sendCodeReq.getUserId());
            signCodeMapper.insert(signCode);
        }
        return result;
    }

    /**
     * 指定手机号批量文件签章
     * 
     * @param userId 用户 id
     * @param accountId 用户对应 e 签宝账户
     * @param mobile 手机号
     * @param code 验证码
     * @param sealId 印模 id
     * @param signInfos 签章文件列表
     * @return 签章后文件列表
     */
    public ServiceResult<MultiSignedResultDTO> signPdf(Integer userId, String accountId, String mobile, String code,
        Integer sealId, List<SigningParamBean> signInfos) {
        BatchSignPdfAppointMobileReq req = new BatchSignPdfAppointMobileReq();
        req.setAccountId(accountId);
        req.setSealId(sealId);
        req.setMobile(mobile);
        req.setCode(code);
        req.setSignInfos(signInfos);
        req.setTraceId(IDUtil.getSecureRandomId());
        req.setChannel(SystemConstant.CHANNEL);
        req.setOperationUserId(userId);
        req.setRequestTime(new Date());

        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "移动审批调用电子签章-指定手机号签章服务,reqParams: {}",
            req);
        ServiceResult<MultiSignedResultDTO> serviceResult = signService.batchSignAppointMobilePdfReq(req);
        if (serviceResult.isSuccess()) {
            return serviceResult;
        }
        throw new BusinessException(serviceResult.getErrorMsg(), serviceResult.getErrorCode());
    }

    /**
     * 查询印模信息
     * 
     * @param userId 用户 id
     * @param sealId 印模 id
     * @return 印模信息
     */
    public SealInfoDTO getSealById(Integer userId, Integer sealId) {
        UserSealReq req = new UserSealReq();
        req.setId(sealId);
        req.setTraceId(IDUtil.getSecureRandomId());
        req.setChannel(SystemConstant.CHANNEL);
        req.setOperationUserId(userId);
        req.setRequestTime(new Date());
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "移动审批调用合约中心查询印模详情服务,reqParams: {}",
            req);
        ServiceResult<UserSealDTO> serviceResult = sealService.getUserSeal(req);
        if (serviceResult.isSuccess()) {
            UserSealDTO result = serviceResult.getResult();
            SealInfoDTO sealInfoDTO = mapper.map(result, SealInfoDTO.class);
            UserInfoDto userInfo =
                userCenterService.getUserInfo(result.getUserId(), SystemConstant.CHANNEL, userId, null);
            sealInfoDTO.setUserName(userInfo.getUserBaseInformationDto().getUserName());
            return sealInfoDTO;
        }
        throw new BusinessException(serviceResult.getErrorMsg(), serviceResult.getErrorCode());
    }

}
